"""
根据excel 第二行数据为文件名进行匹配文件 第一行+_加原文件 进行重名名
"""
import os
from openpyxl import load_workbook


def rename_file():
    path = os.getcwd()
    filename_list = os.listdir(path)
    excel_name = [excelname for excelname in filename_list if excelname.endswith((".xls", ".xlsx"))][0]
    # 打开excel
    excel_path = os.path.join(path, excel_name)
    workbook = load_workbook(excel_path)
    sheet = workbook.worksheets[0]
    name_list = []
    key_list = []
    for i in range(2, sheet.max_row + 1):
        key = sheet.cell(i, 2).value
        value = sheet.cell(i, 1).value
        if key is None or value is None:
            continue
        name_list.append(value)
        key_list.append(key)
    for filename in filename_list:
        pure_filename = os.path.splitext(filename)[0]
        for i, key in enumerate(key_list):
            if pure_filename in key:
                origin_filepath = os.path.join(path, filename)
                des_name = "IP" + str(name_list[i]) + "_" + filename
                des_filepath = os.path.join(path, des_name)
                print("重命名：%s -> %s" % (filename, des_name))
                os.rename(origin_filepath, des_filepath)
                break
    print("------------完成-------------")


if __name__ == '__main__':
    rename_file()
